import { login_api } from '@/services/user';
import { history, useModel } from '@umijs/max';
import { Button, Form, Input } from 'antd';
import { flushSync } from 'react-dom';
import styles from './index.less';

const LoginView: React.FC = () => {
  const { setInitialState } = useModel('@@initialState');

  const onFinish = async (values: any) => {
    // console.log(values);
    const res = await login_api(values);
    console.log(res);
    res.data.type = res.data.type ?? '-1';
    res.data.user.photo = res.data.user.photo ?? '';
    flushSync(() => {
      setInitialState((s) => ({
        ...s,
        currentUser: res.data,
      }));
    });

    localStorage.setItem('token', res.data.token);

    const urlParams = new URL(window.location.href).searchParams;
    history.push(urlParams.get('redirect') || '/');

    return;
  };

  return (
    <div className={styles.login}>
      <div className={styles.left}>
        <div className={styles.card}>
          <div className={styles.title}>
            <span>数字科协</span>
          </div>
          <div className={styles.description}>
            <span>即刻，开启轻松办公</span>
          </div>
        </div>
      </div>
      <div className={styles.right}>
        <div className={styles.card}>
          <div className={styles.title}>
            <span>数字科协</span>
          </div>
          <div className={styles.form}>
            <Form
              name="login"
              initialValues={{
                userName: '',
                password: '',
              }}
              onFinish={onFinish}
            >
              <Form.Item
                className={styles.item}
                label="账号"
                name="userName"
                rules={[{ required: true, message: '请输入账号' }]}
              >
                <Input placeholder="请输入账号" size="large" />
              </Form.Item>

              <Form.Item
                className={styles.item}
                label="密码"
                name="password"
                rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input.Password placeholder="请输入密码" size="large" />
              </Form.Item>

              <Form.Item className={styles.item}>
                <Button type="primary" size="large" block htmlType="submit">
                  登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LoginView;
